import { defineStore } from "pinia";

import { store } from "@/store";
import { useTagsViewStore, TagView } from "@/store/modules/tagsView";

import { getCourseInfoApi, isValidCourseParamsApi } from "@/api/course";
const tagsViewStore = useTagsViewStore();

export const useStudyStore = defineStore("study", () => {
  // state
  const courseId = ref();
  const courseName = ref("");
  const leaderName = ref("");
  const wallpaperUrl = ref("");

  // 登陆学习课程信息
  function studyCourse(id: number) {
    return new Promise<void>((resolve, reject) => {
      courseId.value = id;
      resolve();
    });
  }

  function isValidCourseParams(id: number) {
    return new Promise<Boolean>((resolve, reject) => {
      isValidCourseParamsApi(id)
        .then((response) => {
          courseId.value = id;
          resolve(true);
        })
        .catch((error) => {
          reject("课程信息不合法，请勿修改地址栏");
        });
    });
  }

  function getCourseInfo() {
    return new Promise<void>((resolve, reject) => {
      getCourseInfoApi(courseId.value)
        .then(({ data }) => {
          if (!data) {
            return reject("Verification failed, please Login again.");
          }
         
          courseName.value = data.name!;
          wallpaperUrl.value = data.wallpaperUrl!;
          leaderName.value = data.leaderName!;
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 重置课程信息
  function resetCourse() {
    courseId.value = null;
    courseName.value = "";
    wallpaperUrl.value = "";
    leaderName.value = "";
  }

  // 重置课程信息
  function removeCache() {
    return new Promise<void>((resolve, reject) => {
      const views = tagsViewStore.visitedViews.filter((view: TagView) => {
        return view.meta?.layout === "StudyLayout";
      });

      tagsViewStore
        .delViews(views)
        .then((res: any) => {
          resolve();
        })
        .catch(() => {
          reject();
        });
    });
  }

  return {
    courseId,
    courseName,
    wallpaperUrl,
    leaderName,
    isValidCourseParams,
    getCourseInfo,
    resetCourse,
    studyCourse,
    removeCache,
  };
});

// 非setup
export function useStudyStoreHook() {
  return useStudyStore(store);
}
